<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :title="getTitle"
    :width="adaptiveWidth"
    @ok="handleSubmit"
    :showFooter="showFooter"
    destroyOnClose
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './riskInfo.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { getIntoById, saveRiskInfo } from './riskInfo.api';
  import { useDrawerAdaptiveWidth } from '/@/hooks/jeecg/useAdaptiveWidth';

  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  // const attrs = useAttrs();
  const isUpdate = ref(true);
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const showFooter = ref(true);
  let ID = ref();
  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    showFooter.value = data?.showFooter ?? true;
    setDrawerProps({ confirmLoading: false, showFooter: showFooter.value });
    isUpdate.value = !!data?.isUpdate;
    ID.value = data.record.id;
    if (unref(isUpdate)) {
      //获取详情
      data.record = await getIntoById({ id: data.record.id });
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter.value });
  });
  //获取标题
  const getTitle = computed(() => (!unref(isUpdate) ? '编辑' : '详情'));
  const { adaptiveWidth } = useDrawerAdaptiveWidth();

  //提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({ confirmLoading: true });
      let isUpdateVal = unref(isUpdate);
      //提交表单
      await saveRiskInfo({ id: ID.value, ...values }, isUpdateVal);
      //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success', { isUpdateVal, values });
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
